package com.travelsky.login.infrastructure;

import com.travelsky.login.domain.Account;
import com.travelsky.login.domain.Department;
import com.travelsky.login.domain.User;
import com.travelsky.login.domain.UserRepository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

@Repository
class UserRepositoryAdapter implements UserRepository {

  private final JdbcTemplate jdbcTemplate;

  @Autowired
  public UserRepositoryAdapter(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }

  /**
   * 通过用户名查找用户信息
   *
   * @param userId 用户名
   * @return 用户信息
   */
  @Override
  public User findBy(String userId) {
    String sql = "SELECT U.USERID USERID,U.PASSWORD PASSWORD,U.USERNAME USERNAME,U.MOBILE MOBILE,"
        + "U.LOCKED ULOCKED,U.LASTLOGINTIME LASTLOGINTIME,"
        + "DEP.DEPARTMENTID DEPARTMENTID,DEP.DEPARTMENTNAME DEPARTMENTNAME,DEP.LOCKED DEPLOCKED"
        + " FROM USER U,DEPARTMENT DEP "
        + "WHERE U.USERID = ? AND U.DEPARTMENTID = DEP.DEPARTMENTID";
    List<User> accounts = jdbcTemplate.query(sql, new Object[]{userId}, (rs, i) -> createUser(rs));
    if (CollectionUtils.isEmpty(accounts)) {
      return null;
    }
    return accounts.get(0);
  }

  private User createUser(ResultSet rs) throws SQLException {
    return new User().setAccount(createAccount(rs))
    .setDepartment(createDepartment(rs))
    .setMobile(rs.getString("MOBILE"))
    .setUserName(rs.getString("USERNAME"));
  }

  private Account createAccount(ResultSet rs) throws SQLException {
    return new Account()
        .setUserId(rs.getString("USERID"))
        .setLastLoginTime(rs.getString("LASTLOGINTIME"))
        .setLocked("1".equals(rs.getString("ULOCKED")))
        .setPassword(rs.getString("PASSWORD"));
  }

  private Department createDepartment(ResultSet rs) throws SQLException {
    return new Department()
        .setDepartmentId(rs.getString("DEPARTMENTID"))
    .setDepartmentName(rs.getString("DEPARTMENTNAME"))
        .setLocked("1".equals(rs.getString("DEPLOCKED")));
  }
}
